<template>
  <div>
    <Header></Header>

    <div class='r-content'>
      <el-form :model="blog_edit" :rules="rules" ref="blog_edit" label-width="100px" class="demo-ruleForm">
        <el-form-item label="标题" prop="title">
          <el-input v-model="blog_edit.title"></el-input>
        </el-form-item>

        <el-form-item label="摘要" prop="description">
          <el-input type="textarea" v-model="blog_edit.description"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <mavon-editor v-model="blog_edit.content"></mavon-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('blog_edit')">确定</el-button>
          <el-button @click="resetForm('blog_edit')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>
import Header from "../components/Header";

export default {
  name: "BlogEdit",
  components: {Header},
  data() {
    return {
      blog_edit: {
        id: '',
        title: '',
        description: '',
        content: '',
      },
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 5, max: 25, message: '长度在 5 到 25 个字符', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入摘要', trigger: 'blur'}
        ],
        content: [
          {required: true, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var _this = this;

          this.$axios.post('/blog/edit', _this.blog_edit, {
            headers: {
              "Authorization": localStorage.getItem('token')
            }
          }).then(res => {
            _this.$alert('操作成功', '提示', {
              confirmButtonText: '确定',
              callback: function () {
                _this.$router.push({name: 'Blogs'})
              }
            });
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  created() {
    const blogId = this.$route.params.blogId;
    const _this = this;
    if (blogId) {
      this.$axios.get('/blog/' + blogId).then(res => {
        let blog = res.data.data;
        _this.blog_edit.id = blog.id;
        _this.blog_edit.title = blog.title;
        _this.blog_edit.description = blog.description;
        _this.blog_edit.content = blog.content;
      })
    }
  }
}
</script>

<style scoped>
.r-content {
  width: 960px;
  margin: 0 auto;
  text-align: center;
  margin-top: 30px;
}
</style>
